package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.CreditRepairType;
import com.py.credit.entity.GuijiEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CreditRepairTableFieldEnum;
import com.py.credit.entity.enums.CreditRepairTableFieldHeiEnum;
import com.py.credit.service.CreditRepairService;
import com.py.credit.service.LhjcNetworkMapService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.TableService;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 数说奖惩相关图表
 */
@RestController
@RequestMapping("/jcmap")
public class LhjcNetworkMapController {

    @Autowired
    private LhjcNetworkMapService lhjcNetworkMapService;

    @Autowired
    private RemoteBaseService remoteBaseService;
    
    private final static String FRONT_TABLE_ID = "creditFixTable";
    
    @Autowired
    private CreditRepairService creditRepairService;
    
    @Autowired
    private TableService tableService;

    /**
     * 频道首页数说奖惩图表
     *
     * @param jclb 奖惩类别：C:惩戒 J:激励
     * @return
     */
    @RequestMapping(value = "/reproachChart.json")
    public RestServiceResult getReproachChart(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb) {
        RestServiceResult restServiceResult = new RestServiceResult();
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("overallSituationChart", lhjcNetworkMapService.selectOverallSituation(jclb));
        if (jclb.equals("C")) {
            map.put("frChart", lhjcNetworkMapService.selectFrHeimdIndustry(null));
            map.put("zrrSexChart", lhjcNetworkMapService.selectZrrHeimdSex());
            map.put("zrrAgeChart", lhjcNetworkMapService.selectZrrHeimdAge(null));
        } else {
            map.put("frChart", lhjcNetworkMapService.selectFrHongmdIndustry(null));
            map.put("zrrSexChart", lhjcNetworkMapService.selectZrrHongmdSex());
            map.put("zrrAgeChart", lhjcNetworkMapService.selectZrrHongmdAge(null));
        }

        restServiceResult.setData(map);
        return restServiceResult;
    }

    /**
     * 数说奖惩总体情况图表
     *
     * @param jclb 奖惩类别：C:惩戒 J:激励
     * @return
     */
    @RequestMapping(value = "/overallSituationChart.json")
    public RestServiceResult selectOverallSituation(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb) {
        RestServiceResult restServiceResult = new RestServiceResult();

        restServiceResult.setData(lhjcNetworkMapService.selectOverallSituation(jclb));
        return restServiceResult;
    }

    /**
     * 数说奖惩法人情况图表
     *
     * @param jclb 奖惩类别：C:惩戒 J:激励
     * @return
     */
    @RequestMapping(value = "/frChart.json")
    public RestServiceResult getFrChart(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb) {
        RestServiceResult restServiceResult = new RestServiceResult();
        Map<String, Object> map = new HashMap<String, Object>();

        if (jclb.equals("C")) {
            map.put("frDistribution", lhjcNetworkMapService.selectFrHeimdIndustry(null));

            //获取前6个月
            List<Map<String, Object>> frTendencyList = new ArrayList<Map<String, Object>>();
            LinkedList<String> previousMonthList = DateUtils.getPreviousMonth(6L);
            for (String previousMonth : previousMonthList
                    ) {
                Map<String, Object> tendencyMap = new HashMap<String, Object>();
                tendencyMap.put("date", previousMonth);
                tendencyMap.put("value", lhjcNetworkMapService.selectFrHeimdIndustry(previousMonth));
                frTendencyList.add(tendencyMap);
            }

            map.put("frTendency", frTendencyList);
        } else {
            map.put("frDistribution", lhjcNetworkMapService.selectFrHongmdIndustry(null));

            //获取前6个月
            List<Map<String, Object>> frTendencyList = new ArrayList<Map<String, Object>>();
            LinkedList<String> previousMonthList = DateUtils.getPreviousMonth(6L);
            for (String previousMonth : previousMonthList
                    ) {
                Map<String, Object> tendencyMap = new HashMap<String, Object>();
                tendencyMap.put("date", previousMonth);
                tendencyMap.put("value", lhjcNetworkMapService.selectFrHongmdIndustry(previousMonth));
                frTendencyList.add(tendencyMap);
            }

            map.put("frTendency", frTendencyList);
        }

        restServiceResult.setData(map);
        return restServiceResult;
    }

    /**
     * 数说奖惩自然人情况图表
     *
     * @param jclb 奖惩类别：C:惩戒 J:激励
     * @return
     */
    @RequestMapping(value = "/zrrChart.json")
    public RestServiceResult getZrrChart(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb) {
        RestServiceResult restServiceResult = new RestServiceResult();
        Map<String, Object> map = new HashMap<String, Object>();

        LinkedHashMap zrrAnalysis = new LinkedHashMap();
        if (jclb.equals("C")) {
            map.put("zrrSex", lhjcNetworkMapService.selectZrrHeimdSex());
            map.put("zrrAge", lhjcNetworkMapService.selectZrrHeimdAge(null));
            zrrAnalysis.put("manAge", lhjcNetworkMapService.selectZrrHeimdAge("男"));
            zrrAnalysis.put("womanAge", lhjcNetworkMapService.selectZrrHeimdAge("女"));
            map.put("zrrAnalysis", zrrAnalysis);
        } else {
            map.put("zrrSex", lhjcNetworkMapService.selectZrrHongmdSex());
            map.put("zrrAge", lhjcNetworkMapService.selectZrrHongmdAge(null));
            zrrAnalysis.put("manAge", lhjcNetworkMapService.selectZrrHongmdAge("男"));
            zrrAnalysis.put("womanAge", lhjcNetworkMapService.selectZrrHongmdAge("女"));
            map.put("zrrAnalysis", zrrAnalysis);
        }

        restServiceResult.setData(map);
        return restServiceResult;
    }
    
    @RequestMapping(value = "/guiji.json")
    public RestServiceResult<List<GuijiEntity>> getXyjgGuiji(@RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
    		@RequestParam(defaultValue = "", required = true, value = "bm") String bm,
    		@RequestParam(defaultValue = "", required = true, value = "type") String type,
    		HttpServletRequest request) {
    
    	List<GuijiEntity> list= new ArrayList<GuijiEntity>();
    	
    	
    	if("C".equals(type)){
    		
    		//信用承诺
    		List<Map> xycnList = lhjcNetworkMapService.getXycn(ztmc,null,"100000");
    		for(Map map : xycnList){
    			if(map != null){
    				GuijiEntity guijiEntity = new GuijiEntity();
    				if(null == map.get("report_time")){
    					guijiEntity.setTime("");
    				}else{
    					guijiEntity.setTime(String.valueOf(map.get("report_time")));
    				}
    				
    				guijiEntity.setName("信用承诺");
    				guijiEntity.setMessgae(map.get("report_dept")+"上传此企业的信用承诺");
    				list.add(guijiEntity);
    			}
    		}
    		
    		//行政处罚
    		List<Map> xzcfList = lhjcNetworkMapService.getXzcf(ztmc,null,"C");
    		for(Map map : xzcfList){
    			if(map != null){
    				GuijiEntity guijiEntity = new GuijiEntity();
    				if(null == map.get("CF_JDRQ")){
    					guijiEntity.setTime("");
    				}else{
    					guijiEntity.setTime(String.valueOf(map.get("CF_JDRQ")));
    				}
    				guijiEntity.setName("行政处罚");
    				guijiEntity.setMessgae("进行行政处罚");
    				list.add(guijiEntity);
    			}
    		}
    		
    		//黑名单
    		List<Map> hmdList = lhjcNetworkMapService.getHmd(ztmc,null,"C");
    		for(Map map : hmdList){
    			if(map != null){
    				GuijiEntity guijiEntity = new GuijiEntity();
    				
    				if(null == map.get("PUBLISH_DATE")){
    					guijiEntity.setTime("");
    				}else{
    					guijiEntity.setTime(String.valueOf(map.get("PUBLISH_DATE")));
    				}
    				
    				
    				guijiEntity.setName("黑名单");
    				guijiEntity.setMessgae("发起黑名单");
    				list.add(guijiEntity);
    			}
    		}
    		
    		//信用监管
    		RestServiceResult<List<Map>> resXyjg = remoteBaseService.getXyjg(ztmc, null, "C",HttpServletHelper.getUserToken(request));
    		if (RestServiceResult.CODE_SUCCESS == resXyjg.getCode()) {
   			 List<Map> xypjList = resXyjg.getData();
   			 if(xypjList != null){
   				 for(Map map : xypjList){
   		    			if(map != null){
   		    				
   		    				String creat_time = String.valueOf(map.get("creat_time"));
		    				if(creat_time != null && !"".equals(creat_time)){
		    					Long timeLong = Long.parseLong(creat_time);
		    			        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		    			        Date date;
		    					try {
		    						date = format.parse(format.format(timeLong));
		    						creat_time =  format.format(date);
		    					} catch (ParseException e) {
		    						e.printStackTrace();
		    						creat_time = null;
		    					}
		    				}
   		    				
   		    				GuijiEntity guijiEntity = new GuijiEntity();
   		    				guijiEntity.setTime(creat_time);
   		    				guijiEntity.setName("信用监管");
   		    				guijiEntity.setMessgae(map.get("officeName") + "发起对此企业的信用监管");
   		    				list.add(guijiEntity);
   		    			}
   		    		}
   			 }
   		 }
    		
    		
    		//联合惩戒
    		 RestServiceResult<List<Map>> reslhcf = remoteBaseService.getlhcf(ztmc, null, "C",HttpServletHelper.getUserToken(request));
    		 if (RestServiceResult.CODE_SUCCESS == reslhcf.getCode()) {
    			 List<Map> lhjcList = reslhcf.getData();
    			 if(lhjcList != null){
    				 for(Map map : lhjcList){
    		    			if(map != null){
    		    				GuijiEntity guijiEntity = new GuijiEntity();
    		    				String feedbackTime = String.valueOf(map.get("feedbackTime"));
    		    				if(feedbackTime != null && !"".equals(feedbackTime)){
    		    					Long timeLong = Long.parseLong(feedbackTime);
    		    			        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    		    			        Date date;
    		    					try {
    		    						date = format.parse(format.format(timeLong));
    		    						 feedbackTime =  format.format(date);
    		    					} catch (ParseException e) {
    		    						e.printStackTrace();
    		    						feedbackTime = null;
    		    					}
    		    				}
    		    				
    		    				guijiEntity.setTime(feedbackTime);
    		    				guijiEntity.setName("联合惩戒");
    		    				guijiEntity.setMessgae(String.valueOf(map.get("OFFICE_NAME")) + "反馈" + String.valueOf(map.get("feedbackMess")));
    		    				list.add(guijiEntity);
    		    			}
    		    		}
    			 }
    		 }
    		
    	}else if("P".equals(type)){
    		
    		//信用承诺
    		List<Map> xycnList = lhjcNetworkMapService.getXycn(ztmc,bm,"100001");
    		for(Map map : xycnList){
    			if(map != null){
    				GuijiEntity guijiEntity = new GuijiEntity();
    				
    				if(null == map.get("report_time")){
    					guijiEntity.setTime("");
    				}else{
    					guijiEntity.setTime(String.valueOf(map.get("report_time")));
    				}
    				
    				
    				guijiEntity.setName("信用承诺");
    				guijiEntity.setMessgae(map.get("report_dept")+"上传此人的信用承诺");
    				list.add(guijiEntity);
    			}
    		}
    		//行政处罚
    		List<Map> xzcfList = lhjcNetworkMapService.getXzcf(ztmc,bm,"C");
    		for(Map map : xzcfList){
    			if(map != null){
    				GuijiEntity guijiEntity = new GuijiEntity();
    				if(null == map.get("CF_JDRQ")){
    					guijiEntity.setTime("");
    				}else{
    					guijiEntity.setTime(String.valueOf(map.get("CF_JDRQ")));
    				}
    				guijiEntity.setName("行政处罚");
    				guijiEntity.setMessgae("进行行政处罚");
    				list.add(guijiEntity);
    			}
    		}
    		
    		//黑名单
    		List<Map> hmdList = lhjcNetworkMapService.getHmd(ztmc,bm,"C");
    		for(Map map : hmdList){
    			if(map != null){
    				GuijiEntity guijiEntity = new GuijiEntity();
    				if(null == map.get("PUBLISH_DATE")){
    					guijiEntity.setTime("");
    				}else{
    					guijiEntity.setTime(String.valueOf(map.get("PUBLISH_DATE")));
    				}
    				guijiEntity.setName("黑名单");
    				guijiEntity.setMessgae("发起黑名单");
    				list.add(guijiEntity);
    			}
    		}
    		//信用监管
    		//联合惩戒
    		RestServiceResult<List<Map>> reslhcf = remoteBaseService.getlhcf(ztmc, bm, "P",HttpServletHelper.getUserToken(request));
   		 if (RestServiceResult.CODE_SUCCESS == reslhcf.getCode()) {
   			 List<Map> lhjcList = reslhcf.getData();
   			 if(lhjcList != null){
   				 for(Map map : lhjcList){
   		    			if(map != null){
   		    				GuijiEntity guijiEntity = new GuijiEntity();
   		    				
   		    				String feedbackTime = String.valueOf(map.get("feedbackTime"));
		    				if(feedbackTime != null && !"".equals(feedbackTime)){
		    					Long timeLong = Long.parseLong(feedbackTime);
		    			        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		    			        Date date;
		    					try {
		    						date = format.parse(format.format(timeLong));
		    						 feedbackTime =  format.format(date);
		    					} catch (ParseException e) {
		    						e.printStackTrace();
		    						feedbackTime = null;
		    					}
		    				}
		    				
   		    				guijiEntity.setTime(feedbackTime);
   		    				guijiEntity.setName("联合惩戒");
   		    				guijiEntity.setMessgae(String.valueOf(map.get("OFFICE_NAME")) + "反馈" + String.valueOf(map.get("feedbackMess")));
   		    				list.add(guijiEntity);
   		    			}
   		    		}
   			 }
   		 }
    		
    	}
    	Collections.sort(list);
    	
    	return new RestServiceResult<>(list);
    }
    
    
    @RequestMapping(value = "/getTableList.json")
    public RestServiceResult<List<Map<String, Object>>> getTableList(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            Page page, HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + tableId);
            } else {
                ExceptionLogger.error("LhjcNetworkMapController#getTableList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("LhjcNetworkMapController#getTableList", "未获取到当前用户信息！");
        }
        List<String> showColumns;
        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            showColumns = (configColumns == null || configColumns.length == 0)
                    ? CreditRepairTableFieldEnum.getDefaultShowColumnEN(tableId.toString()) : Arrays.asList(configColumns);
        } else {
            showColumns = (configColumns == null || configColumns.length == 0)
                    ? CreditRepairTableFieldHeiEnum.getDefaultShowColumnEN(tableId.toString()) : Arrays.asList(configColumns);
        }
        String[] additionalColumns = {"id", "record_id"};
        List<Map<String, Object>> tableList = creditRepairService.getByConditionForPage(tableId.toString(), showColumns,
                additionalColumns, condition, page);
        return new RestServiceResult<>(page.getTotalCount(), tableList);

    }
    
    @RequestMapping(value = "/getOptionalColumns.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColumns(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId) {
        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            return new RestServiceResult<>(CreditRepairTableFieldEnum.getAdvancedConditionColumns(tableId.toString()));
        }else {
            return new RestServiceResult<>(CreditRepairTableFieldHeiEnum.getAdvancedConditionColumns(tableId.toString()));
        }
    }

    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns(
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId) {
        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            return new RestServiceResult<>(CreditRepairTableFieldEnum.getAdvancedConditionColumns(tableId.toString()));
        }else {
            return new RestServiceResult<>(CreditRepairTableFieldHeiEnum.getAdvancedConditionColumns(tableId.toString()));
        }

    }
    
    @RequestMapping(value = "/addShowColumns.json")
    public RestServiceResult<String> addShowColumns(@RequestParam(value = "columns", required = true) String[] columns,
                                                    @RequestParam(value = "tableId", defaultValue = "100000", required = true) String tableId,
                                                    HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID + "_" + tableId, columns);
            } else {
                ExceptionLogger.error("LhjcNetworkMapController#addShowColumns", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("LhjcNetworkMapController#addShowColumns", "未获取到当前用户信息！");
        }
        return new RestServiceResult<>();
    }

    @RequestMapping(value = "/exportList.json")
    public void exportCommoncontentList(
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
            @RequestParam(value = "tableId", defaultValue = "210001", required = true) Integer tableId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletResponse response) throws IOException {

        page.setLimit(1000);

        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<Map<String, Object>> tableList = creditRepairService.getByConditionForPage(tableId.toString(), showColumns, null,
                condition, page);
        List<OptionalColumn> optionalColumns;

        if (CreditRepairType.FR_XZCF.equals(tableId) || CreditRepairType.ZRR_XZCF.equals(tableId)) {
            optionalColumns = CreditRepairTableFieldEnum.getOptionalColumns(tableId.toString());
        }else {
            optionalColumns = CreditRepairTableFieldHeiEnum.getOptionalColumns(tableId.toString());
        }

        ExcelUtil.downloadExcel(response, tableList, "信用修复历史列表", "信用修复历史列表", showColumns, optionalColumns);

    }
    
    @RequestMapping(value = "/detail.json")
    public RestServiceResult<Object> detail(
            @RequestParam(value = "id", defaultValue = "", required = true) String recordId,
            @RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId) {
        String tableName = "t_" + tableService.queryCubeById(tableId).getResourceId();
        Map<String, Object> records = creditRepairService.getRecordById(recordId, tableName);
        return new RestServiceResult<>(records);
    }
    
    
    @RequestMapping(value = "/getTybmByqymc.json")
    public RestServiceResult<Object> getTybmByqymc(
            @RequestParam(value = "ztName", defaultValue = "", required = true) String ztName,
            @RequestParam(value = "ztBm", defaultValue = "", required = false) String ztBm,
            @RequestParam(value = "kid", defaultValue = "", required = true) String kid) {
    	
        String records = lhjcNetworkMapService.getTybmByqymc(ztName, ztBm,kid);
        return new RestServiceResult<>(records);
    }
}
